package com.sunday.pinxinghui.model.order;

import android.content.Intent;
import android.os.Bundle;
import android.text.InputType;
import android.text.TextUtils;
import android.view.View;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.sunday.common.base.BaseActivity;
import com.sunday.common.imageselector.MultiImageSelectorActivity;
import com.sunday.common.model.ResultDO;
import com.sunday.common.utils.ImageUtils;
import com.sunday.common.utils.StringUtils;
import com.sunday.common.utils.ToastUtils;
import com.sunday.common.utils.UploadUtils;
import com.sunday.common.widgets.NoScrollGridView;
import com.sunday.pinxinghui.R;
import com.sunday.pinxinghui.adapter.GradImageAdapter;
import com.sunday.pinxinghui.base.BaseApplication;
import com.sunday.pinxinghui.entity.Images;
import com.sunday.pinxinghui.entity.Order;
import com.sunday.pinxinghui.network.ApiClient;

import java.math.BigDecimal;
import java.math.RoundingMode;
import java.util.ArrayList;
import java.util.List;

import butterknife.Bind;
import butterknife.ButterKnife;
import butterknife.OnClick;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;

/**
 * Created by 刘涛 on 2017/8/20.
 */

public class ApplyRefundActivity extends BaseActivity {


    @Bind(R.id.title_view)
    TextView titleView;
    @Bind(R.id.edit_money)
    EditText editMoney;
    @Bind(R.id.max_money)
    TextView maxMoney;
    @Bind(R.id.edit_reason)
    EditText editReason;
    @Bind(R.id.edit_mobile)
    EditText editMobile;
    @Bind(R.id.txt_upload_img)
    TextView txtUploadImg;
    @Bind(R.id.grid_view)
    NoScrollGridView gridView;
    @Bind(R.id.txt_reason)
    TextView txtReason;


    private Order order;
    private List<String> imgs = new ArrayList<>();
    private List<String> netImgs=new ArrayList<>();
    private int type;
    private GradImageAdapter adapter;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_apply_refund);
        ButterKnife.bind(this);
        type = getIntent().getIntExtra("type", 1);
        titleView.setText(type == 1 ? "退款" : "退货");
        order= (Order) getIntent().getSerializableExtra("order");
        editMoney.setInputType(InputType.TYPE_CLASS_NUMBER | InputType.TYPE_NUMBER_FLAG_DECIMAL);
        maxMoney.setText(String.format("最多可退%s元", order.getAmountFee().setScale(2, RoundingMode.HALF_UP)));
        txtReason.setText(type == 1 ? "退款原因" : "退货原因");
        editReason.setHint(type == 1 ? "请输入退款原因" : "请输入退货原因");
        String mobile = BaseApplication.getInstance().getMember().getMobile();
        editMobile.setText(mobile);
        txtUploadImg.setVisibility(type == 1 ? View.GONE : View.VISIBLE);
        gridView.setVisibility(type == 1 ? View.GONE : View.VISIBLE);
        adapter = new GradImageAdapter(3, imgs, 0);
        gridView.setAdapter(adapter);
        adapter.setOnClickListener(onClickListener);
    }

    View.OnClickListener onClickListener=new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            switch (v.getId()){
                case R.id.photo_add:
                    if (imgs.size() == (int) v.getTag()) {
                        toImage(3 - imgs.size());
                    }
                    break;
                case R.id.photo_delete:
                    imgs.remove((int) v.getTag());
                    adapter.notifyDataSetChanged();
                    break;
            }
        }
    };

    public void toImage(int max) {
        intent = new Intent(mContext, MultiImageSelectorActivity.class);
        intent.putExtra(MultiImageSelectorActivity.EXTRA_SELECT_COUNT, max);
        intent.putExtra(MultiImageSelectorActivity.EXTRA_SELECT_MODE, MultiImageSelectorActivity.MODE_MULTI);
        startActivityForResult(intent, 1111);
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == RESULT_OK) {
            switch (requestCode) {
                case 1111:
                    ArrayList<String> mSelectPath = data.getStringArrayListExtra(MultiImageSelectorActivity.EXTRA_RESULT);
                    for (String path : mSelectPath) {
                        imgs.add(ImageUtils.getCompressImagePath(path));
                    }
                    adapter.notifyDataSetChanged();
                    return;
            }
        }
    }



    @OnClick(R.id.btn_submit)
    void save() {
        final String reason = editReason.getText().toString().trim();
        String mobile = editMobile.getText().toString().trim();
        String amount = editMoney.getText().toString().trim();
        if (TextUtils.isEmpty(reason)) {
            ToastUtils.showToast(mContext, "请填写具体原因");
            return;
        }
        if (!StringUtils.isMobileNO(mobile)||TextUtils.isEmpty(mobile)) {
            ToastUtils.showToast(mContext, "请填写正确手机号");
            return;
        }
        if (TextUtils.isEmpty(amount)) {
            ToastUtils.showToast(mContext, "请填写具体金额");
            return;
        }
        if (BigDecimal.valueOf(Double.valueOf(amount)).compareTo(order.getTotalFee())>0){
            ToastUtils.showToast(mContext, "已超出可提现最大金额");
            return;
        }

        if (type==2&&imgs.size()>0){
            UpImgae();
        }else {
            submitApply();
        }

    }

    private void UpImgae(){
        showLoadingDialog(0);
        Call<ResultDO<List<Images>>> call = ApiClient.getApiAdapter().saveImages(UploadUtils.getRequestBody(imgs));
        call.enqueue(new Callback<ResultDO<List<Images>>>() {
            @Override
            public void onResponse(Call<ResultDO<List<Images>>> call, Response<ResultDO<List<Images>>> response) {
                if (response.body() == null || isFinish) {
                    return;
                }
                dissMissDialog();
                if (response.body().getCode() == 0 && response.body().getResult() != null) {
                    netImgs.clear();
                    for (Images images:response.body().getResult()){
                        netImgs.add(images.getSaveUrl());
                    }
                    submitApply();
                }
            }

            @Override
            public void onFailure(Call<ResultDO<List<Images>>> call, Throwable t) {

            }
        });
    }

    private void submitApply(){
         String reason = editReason.getText().toString().trim();
        String mobile = editMobile.getText().toString().trim();
        String amount = editMoney.getText().toString().trim();
        showLoadingDialog(0);
        Call<ResultDO> call = ApiClient.getApiAdapter().applyRefund(order.getOrderId(), type, reason, mobile, null, amount,StringUtils.listToString(netImgs));
        call.enqueue(new Callback<ResultDO>() {
            @Override
            public void onResponse(Call<ResultDO> call, Response<ResultDO> response) {
                if (isFinish || response.body() == null) {
                    return;
                }
                dissMissDialog();
                if (response.body().getCode() == 0) {
                    ToastUtils.showToast(mContext, "提交成功");
                    finish();
                } else {
                    ToastUtils.showToast(mContext, response.body().getMessage());
                }
            }

            @Override
            public void onFailure(Call<ResultDO> call, Throwable t) {
                dissMissDialog();
                ToastUtils.showToast(mContext, R.string.network_error);
            }
        });
    }

}
